package algotrader.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.postgresql.util.PSQLException;

import algotrader.model.Operador;

public class OperadorDao {
	
	public Operador getUser(String user, String senha) {
		Connection con = ConnectionFactory.getConnection();
		try {
			String sql = "select * from operador where login = ? and senha = ?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, user);
			ps.setString(2,senha);
			ResultSet rs = ps.executeQuery();
			if(!rs.next()) return null;
			
			Operador o = new Operador(rs.getInt("id"));
			o.setNome(rs.getString("nome"));
			o.setUsuario(rs.getString("login"));
			o.setSenha(rs.getString("senha"));
			if(rs.next()) return null; // usuario e senha retornou mais de um usuario
			return o;
		} catch (PSQLException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void insereOperador(Operador o) {
		Connection con = ConnectionFactory.getConnection();
		try {
			String sql = "insert into operador (id,nome,login,senha) values (?,?,?,?)";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1,o.getId());
			ps.setString(2,o.getNome());
			ps.setString(3, o.getUsuario());
			ps.setString(4, o.getSenha());
			ps.execute();
		} catch (PSQLException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void removeOperador(int id) {
		Connection con = ConnectionFactory.getConnection();
		try {
			String sql = "delete from operador where id = ?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ps.execute();
		} catch (PSQLException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
